package com.shanghaionstar.activity.webview.handler;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Message;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.shanghaionstar.activity.webview.handler.picture.BitmapUtils;
import com.shanghaionstar.activity.webview.handler.picture.FileUtils;
import com.shanghaionstar.activity.webview.handler.picture.ImportImageItem;
import com.shanghaionstar.activity.webview.handler.picture.SelectPicActivity;
import com.shanghaionstar.activity.webview.handler.picture.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * Created by Rengui Lu on 2017/3/3.
 */
public class UploadPicWebHandler extends ShareReportWebHandler {
    public ValueCallback<Uri[]> uploadMessage;

    private ValueCallback<Uri> mUploadMessage;

    public static final int REQUEST_SELECT_FILE = 100;

    private final static int FILECHOOSER_RESULTCODE = 0x001;

    private void fromLocalSelectedFile() {
//        Intent localIntent = new Intent(mContext, SelectPicActivity.class);
//        startActivityForResult(localIntent, REQUEST_SELECT_FILE);

        Intent localIntent = new Intent(context, SelectPicActivity.class);
        localIntent.putExtra(SelectPicActivity.MAX_NUMBER_IMAGES, 1);
        if (context instanceof CommonWebViewActivity)
            ((CommonWebViewActivity) context).startActivityForResult(localIntent, REQUEST_SELECT_FILE);

    }


    public UploadPicWebHandler(Context context) {
        super(context);
    }

    @Override
    public void handMsg(Message msg) {
        super.handMsg(msg);
        switch (msg.what) {
            case IWebType.TYPE_UPLOAD_PIC:
                init(msg);
                break;
            case IWebType.TYPE_ON_ACTIVITY_RESULT:
                onActivityResult(msg.arg1, msg.arg2, (Intent) msg.obj);
                break;
            case IWebType.TYPE_ON_PAGE_FINISHED:
                initWeb(((CommonWebViewActivity) context).getWebview());
                break;
        }
    }


    private void init(Message msg) {
        CommonWebViewActivity mActivity;
        if (context instanceof CommonWebViewActivity) {
            mActivity = (CommonWebViewActivity) context;
            WebView webview = mActivity.getWebview();
            String linkUrl = ((WebDataEntity) msg.obj).getLinkUrl();
            Map<String, String> header = mActivity.getExtraHeaders();
            webview.loadUrl(linkUrl,header);
        }
    }


    public void initWeb(WebView mWebView) {
        // this.setProgressBarIndeterminateVisibility(true);
        mWebView.setWebChromeClient(new WebChromeClient() {
            // 当WebView进度改变时更新窗口进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // Activity的进度范围在0到10000之间,所以这里要乘以100
//                if (newProgress == 100 && mProgressBar.getVisibility() == View.VISIBLE) {
//                    mProgressBar.setVisibility(View.GONE);
//                } else {
//                    if (mProgressBar.getVisibility() != View.VISIBLE) {
//                        mProgressBar.setVisibility(View.VISIBLE);
//                    }
//                    mProgressBar.setProgress(newProgress);
//                }
            }

            // Android < 3.0 调用这个方法
            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                fromLocalSelectedFile();
            }

            // Android > 3.0 调用这个方法
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                fromLocalSelectedFile();
            }

            // Android > 4.1.1 调用这个方法
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                fromLocalSelectedFile();
            }

            // Android > 5.0 调用这个方法
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                uploadMessage = filePathCallback;
                fromLocalSelectedFile();
                return true;
            }
        });
    }


    public File getNextFileName() {
        File mGalleryFolder = FileUtils.createFolders(FileUtils.IMAGE);
        if (mGalleryFolder != null) {
            if (mGalleryFolder.exists()) {
                File file = new File(mGalleryFolder, "cbclient_" + System.currentTimeMillis() + ".jpg");
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return file;
            }
        }
        return null;
    }




    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_SELECT_FILE:


                    ArrayList<ImportImageItem> importImageItems = data.getParcelableArrayListExtra("imageItems");

                    if (importImageItems != null && importImageItems.size() > 0) {
                        final String[] selectPicPaths = new String[importImageItems.size()];
                        final String[] uploadFilePaths = new String[importImageItems.size()];
                        final Uri[] uris = new Uri[importImageItems.size()];

                        // 拼接
                        for (int i = 0; i < selectPicPaths.length; i++) {
                            selectPicPaths[i] = importImageItems.get(i).getImage();
                            uploadFilePaths[i] = getNextFileName().getAbsolutePath();
                            uris[i] = Uri.parse("file://" + uploadFilePaths[i]);
                        }


                        BitmapUtils.compressPictures(selectPicPaths,
                                uploadFilePaths,
                                768,
                                1366,
                                85,
                                new BitmapUtils.CallBack() {

                                    @Override
                                    public void onSuccess(Object object) {

                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                            if (uploadMessage != null) {
                                                uploadMessage.onReceiveValue(uris);
                                                return;
                                            }
                                        } else {
                                            if (mUploadMessage != null) {
                                                mUploadMessage.onReceiveValue(uris[0]);
                                            }
                                        }
                                        cleanUploadMessage(false);
                                    }

                                    @Override
                                    public void onFailed(String errMsg) {
                                        ToastUtils.showToast_Long(context, errMsg);
                                        cleanUploadMessage(true);
                                    }
                                });

                    }

                    break;

                case FILECHOOSER_RESULTCODE:
                    if (null == mUploadMessage)
                        return;
                    ImportImageItem imageItem = data.getParcelableExtra("imageItem");
                    // file:///mnt/sdcard/tempPhoto.jpg (has extras)
                    data.setData(Uri.parse("file://" + imageItem.getImage()));
                    Uri result = data.getData();
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;

                    break;
                default:
                    break;
            }

        } else {
            if (REQUEST_SELECT_FILE == requestCode) {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    if (mUploadMessage != null) {
                        mUploadMessage.onReceiveValue(null);
                        mUploadMessage = null;
                    }
                } else {
                    if (uploadMessage != null) {
                        uploadMessage.onReceiveValue(null);
                        uploadMessage = null;
                    }
                }
            }
        }

    }




//
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
////        super.onActivityResult(requestCode, resultCode, data);
//
//        if (resultCode == Activity.RESULT_OK) {
//            switch (requestCode) {
//                case REQUEST_SELECT_FILE:
//
//
//                    ArrayList<ImportImageItem> importImageItems = data.getParcelableArrayListExtra("imageItems");
//
//                    if (importImageItems != null && importImageItems.size() > 0) {
//                        final String[] selectPicPaths = new String[importImageItems.size()];
//                        final String[] uploadFilePaths = new String[importImageItems.size()];
//                        final Uri[] uris = new Uri[importImageItems.size()];
//
//                        // 拼接
//                        for (int i = 0; i < selectPicPaths.length; i++) {
//                            selectPicPaths[i] = importImageItems.get(i).getImage();
//                            uploadFilePaths[i] = getNextFileName().getAbsolutePath();
//                            uris[i] = Uri.parse("file://" + uploadFilePaths[i]);
//                        }
//
//
//                        BitmapUtils.compressPictures(selectPicPaths,
//                                uploadFilePaths,
//                                768,
//                                1366,
//                                85,
//                                new BitmapUtils.CallBack() {
//
//                                    @Override
//                                    public void onSuccess(Object object) {
//
//                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                                            if (uploadMessage != null) {
//                                                uploadMessage.onReceiveValue(uris);
//                                                return;
//                                            }
//                                        } else {
//                                            if (mUploadMessage != null) {
//                                                mUploadMessage.onReceiveValue(uris[0]);
//                                            }
//                                        }
//                                        cleanUploadMessage(false);
//                                    }
//
//                                    @Override
//                                    public void onFailed(String errMsg) {
//                                        ToastUtils.showToast_Long(context, errMsg);
//                                        cleanUploadMessage(true);
//                                    }
//                                });
//
//                    }
//
//                    break;
//                default:
//                    break;
//            }
//
//        } else {
//            if (REQUEST_SELECT_FILE == requestCode) {
//
//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//                    if (mUploadMessage != null) {
//                        mUploadMessage.onReceiveValue(null);
//                        mUploadMessage = null;
//                    }
//                } else {
//                    if (uploadMessage != null) {
//                        uploadMessage.onReceiveValue(null);
//                        uploadMessage = null;
//                    }
//                }
//            }
//        }
//
//    }


    private void cleanUploadMessage(boolean nullReceiveValue) {
        if (nullReceiveValue) {
            if (mUploadMessage != null)
                mUploadMessage.onReceiveValue(null);
            if (uploadMessage != null)
                uploadMessage.onReceiveValue(null);
        }
        mUploadMessage = null;
        uploadMessage = null;
    }

}
